const { pool } = require('../config/db');
const { NotFoundError } = require('../middleware/error');

class CategoryModel {
  // 获取所有分类及其子分类
  static async findWithChildren() {
    const [categories] = await pool.execute(
      'SELECT * FROM categories WHERE parent_id IS NULL ORDER BY name'
    );

    // 获取每个顶级分类的子分类
    for (const category of categories) {
      const [children] = await pool.execute(
        'SELECT * FROM categories WHERE parent_id = ? ORDER BY name',
        [category.id]
      );
      category.children = children;
    }

    return categories;
  }

  // 获取指定父分类下的所有子分类
  static async findAll(parentId = null) {
    const [categories] = await pool.execute(
      'SELECT * FROM categories WHERE parent_id = ? ORDER BY name',
      [parentId]
    );
    return categories;
  }

  // 根据ID查找分类
  static async findById(id) {
    const [categories] = await pool.execute(
      'SELECT * FROM categories WHERE id = ?',
      [id]
    );

    if (categories.length === 0) {
      throw new NotFoundError('分类不存在');
    }

    return categories[0];
  }

  // 根据slug查找分类
  static async findBySlug(slug) {
    const [categories] = await pool.execute(
      'SELECT * FROM categories WHERE slug = ?',
      [slug]
    );

    if (categories.length === 0) {
      throw new NotFoundError('分类不存在');
    }

    return categories[0];
  }
}

module.exports = CategoryModel; 